<template>
  <div>
    <h1>Login</h1>
    <form @submit.prevent="login">
      <div>
        <label>Username:</label>
        <input type="text" v-model="username" />
      </div>
      <div>
        <label>Password:</label>
        <input type="password" v-model="password" />
      </div>
      <div v-if="message" class="error">{{ message }}</div>
      <button type="submit">Login</button>
    </form>
  </div>
</template>

<script>
import AuthService from '@/services/AuthService'; // 引入 AuthService

export default {
  data() {
    return {
      username: '',
      password: '',
      message: ''
    };
  },
  methods: {
    async login() {
      try {
        // 调用 AuthService 的 login 方法
        const username = await AuthService.login(this.username, this.password);
        localStorage.setItem('username', username); // 将用户名存入 localStorage
        this.$router.push('/main'); // 登录成功后跳转到主页面
      } catch (error) {
        this.message = error; // 登录失败提示错误信息
      }
    }
  }
};
</script>